package com.xt.wikiperfumapi.Controller.user;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.page.PageMethod;
import com.xt.wikiperfumapi.model.PerfumeInfo;
import com.xt.wikiperfumapi.model.UserCollectPerfumeRef;
import com.xt.wikiperfumapi.model.UserInfo;
import com.xt.wikiperfumapi.model.vo.RestBean;
import com.xt.wikiperfumapi.service.impl.PerfumeInfoServiceImpl;
import com.xt.wikiperfumapi.service.impl.UserCollectPerfumeRefServiceImpl;
import com.xt.wikiperfumapi.service.impl.UserInfoServiceImpl;
import com.xt.wikiperfumapi.util.JedisUtil;
import com.xt.wikiperfumapi.util.JwtUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.beanutils.BeanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/api/userData")
public class UserOption {

    private static final Logger log = LoggerFactory.getLogger(UserOption.class);
    @Resource
    UserInfoServiceImpl userInfoService;

    @Resource
    UserCollectPerfumeRefServiceImpl userCollectPerfumeRefService;//用户收藏香水信息

    @Resource
    PerfumeInfoServiceImpl perfumeInfoService;//香水信息

    @Resource
    JwtUtil jwtUtil;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private JedisUtil jedisUtil;


    @RequestMapping("/myCollectPerfume/{page}/{size}")
    public RestBean getMyCollect(HttpServletRequest request,@PathVariable int page,@PathVariable int size) {
        String uuid = jwtUtil.getJwtUUID(request);
        // 确保分页方法在查询前调用
        PageMethod.startPage(page, size);

// 获取UUID

// 查询用户收藏香水记录并分页
        List<UserCollectPerfumeRef> userCollectPerfumeRefs = userCollectPerfumeRefService.list(
                new QueryWrapper<UserCollectPerfumeRef>()
                        .eq("user_id", uuid)
                        .eq("is_deleted", 0)
                        .orderByDesc("input_time")
        );

        PageInfo pageInfo = new PageInfo<>(userCollectPerfumeRefs);

// 创建一个PerfumeInfo的列表，用来保存香水的详细信息
        List<PerfumeInfo> perfumeInfos = new ArrayList<>();
        pageInfo.getList().forEach(el -> {
            UserCollectPerfumeRef userCollectPerfumeRef=new UserCollectPerfumeRef();
            try {
                BeanUtils.copyProperties(userCollectPerfumeRef,el);
            }catch (Exception e){
                System.out.println(e.getMessage());
            }
            PerfumeInfo perfumeInfo = perfumeInfoService.getById(userCollectPerfumeRef.getPerfumeId());
            if (perfumeInfo != null) {
                perfumeInfos.add(perfumeInfo);
            }
        });

// 创建一个PageInfo对象来包装结果
        pageInfo.setList(perfumeInfos);

// 返回分页结果，PageInfo自动包含总数
        return RestBean.success(pageInfo);


    }

    @RequestMapping("/collect/{id}")
    public RestBean collectIt(HttpServletRequest request, @PathVariable long id) {
        String uuid = jwtUtil.getJwtUUID(request);
        long count = userCollectPerfumeRefService.count(new QueryWrapper<UserCollectPerfumeRef>().eq("user_id", uuid).eq("perfume_id", id));
        if (count == 1) {
            UserCollectPerfumeRef byId = userCollectPerfumeRefService.getOne(new QueryWrapper<UserCollectPerfumeRef>().eq("user_id", uuid).eq("perfume_id", id));
            if (byId.getIsDeleted() == 1) {
                byId.setIsDeleted(0);
                byId.setUpdateTime(new Date());
                return userCollectPerfumeRefService.updateById(byId) ? RestBean.success(byId) : RestBean.failure(500, "server error");
            }
            return RestBean.failure(400, "已经收藏了");
        } else if (count != 0) {
            userCollectPerfumeRefService.remove(new QueryWrapper<UserCollectPerfumeRef>().eq("user_id", uuid).eq("perfume_id", id));
        }
        UserCollectPerfumeRef userCollectPerfumeRef = new UserCollectPerfumeRef();
        userCollectPerfumeRef.setPerfumeId(id);
        userCollectPerfumeRef.setUserId(uuid);
        userCollectPerfumeRef.setInputTime(new Date());
        return userCollectPerfumeRefService.save(userCollectPerfumeRef) ? RestBean.success() : RestBean.failure(500, "server error");
    }

    @RequestMapping("/unCollect/{id}")
    public RestBean unCollectIt(HttpServletRequest request,@PathVariable long id){
        String uuid = jwtUtil.getJwtUUID(request);
        long count = userCollectPerfumeRefService.count(new QueryWrapper<UserCollectPerfumeRef>().eq("user_id", uuid).eq("perfume_id", id));
        if (count == 1) {
            UserCollectPerfumeRef byId = userCollectPerfumeRefService.getOne(new QueryWrapper<UserCollectPerfumeRef>().eq("user_id", uuid).eq("perfume_id", id));
            if (byId.getIsDeleted() == 0) {
                byId.setIsDeleted(1);
                byId.setUpdateTime(new Date());
                return userCollectPerfumeRefService.updateById(byId) ? RestBean.success(byId) : RestBean.failure(500, "server error");
            }
            return RestBean.failure(400, "已经取消收藏了");
        } else if (count != 0) {
            userCollectPerfumeRefService.remove(new QueryWrapper<UserCollectPerfumeRef>().eq("user_id", uuid).eq("perfume_id", id));
        }
        return RestBean.failure(400,"不存在收藏记录");
    }



}
